<template>
	<view>
		<uni-card>
			<detail :formData="formData"></detail>
		</uni-card>
		<view class="form">
			<uni-forms ref="form" :model-value="formData" @submit="onSubmit" :rules="rules" label-width="100%">
				
				<uni-forms-item label="审核是否通过" required name="approved" id="approved">
					<view class="picker2">
						<radio-group @change="closedChange" v-model="formData.approved">
							<label class="closed">
								<radio :value="'0'" :checked="formData.approved == '0'"/>
								是
							</label>
							<label class="closed">
								<radio :value="'1'" :checked="formData.approved == '1'"/>
								否
							</label>
						</radio-group>
					</view>
				</uni-forms-item>
				<uni-forms-item label="不通过原因" name="planFailedReason" required id="planFailedReason" v-if="this.formData.approved === '1'">
					<uni-easyinput type="textarea" maxlength="-1" v-model="formData.planFailedReason" placeholder="请输入不通过原因" />
				</uni-forms-item>
				
				<uni-forms-item label="项目状态" name="projectStatus" required id="projectStatus">
					<uni-data-select v-model="formData.projectStatus" :localdata="dict.type.work_order_status" 
					:clear="false" :disabled="true">
					</uni-data-select>
				</uni-forms-item>
			
				<uni-forms-item label="当前进展" name="currentProgress" required id="currentProgress">
					<uni-easyinput type="textarea" maxlength="-1" v-model="formData.currentProgress" placeholder="当前进展"  :disabled="true"/>
				</uni-forms-item>
			
				<uni-forms-item label="解决方案大类" name="solutionCategory" required id="solutionCategory">
						<uni-easyinput v-model="formData.solutionCategory" placeholder="请输入解决方案大类" :disabled="true"/>
				</uni-forms-item>
			
				<uni-forms-item label="解决方案小类" name="solutionSubclass" required id="currentLink">
						<uni-easyinput v-model="formData.solutionSubclass" placeholder="请输入解决方案小类" :disabled="true"/>
				</uni-forms-item>
			
				<uni-forms-item label="具体方案" name="specificScheme" required id="specificScheme">
					<uni-easyinput type="textarea" maxlength="-1" v-model="formData.specificScheme" placeholder="请输入具体方案" :disabled="true"/>
				</uni-forms-item>
			
				<uni-forms-item label="经度" name="longitude" required id="longitude">
					<uni-easyinput v-model="formData.longitude" placeholder="请输入经度" :disabled="true"/>
				</uni-forms-item>
				<uni-forms-item label="纬度" name="latitude" required id="latitude">
					<uni-easyinput v-model="formData.latitude" placeholder="请输入纬度" :disabled="true"/>
				</uni-forms-item>
				
				<uni-forms-item label="上传照片">
					<view>
						<view style="display: flex;">
							<uni-file-picker ref="pictureUp" :auto-upload="false" :imageStyles="imageStyles"
								:value="imgList" limit="5" @select="upLoadPic($event)" :readonly="true">
							</uni-file-picker>
						</view>
					</view>
				</uni-forms-item>
				
				<view style="height: 60px;"></view>
			</uni-forms>

		</view>
		<view class="btn-row">
			<view style="display: flex;">
<!-- 				<button type="primary" class="btn-save" @tap="onSubmit">不通过</button> -->
				<button type="primary" class="btn-save2" @tap="onSubmit">提交</button>
			</view>
		</view>
	</view>
</template>

<script>
	import detail from '@/pages/common/textview/index.vue'
	import {
		getComplaint,
		userList,
		deleteFileByPath,
		updateComplaint,
		uploadCommonFile,
		writeBytes,
		reassignment,
		sendBack,
		setReviewOpinions,
		solutionSubclassList,
		deleteFile,
	} from '@/api/index.js'
	import searchCombox from '@/pages/common/webview/search-combox.vue';
	import ImageCompressor from '@/node_modules/image-compressor.js'
	import {
		getToken
	} from '@/utils/auth'
	import config from '@/config'
	const videoUrl = config.baseUrl + '/system/complaintFieldFile/writeBytes?path='
	const baseUrl = config.baseUrl
	export default {
		components: {
			detail,
			searchCombox,
		},
		dicts: ['work_order_link', 'solution_category', 'solution_subclass', 'duration_name', 'user_rating',
			'project_status','work_order_status', 'complaints_handling_unit'
		],
		data() {
			return {
				range: [
				          { value: 0, text: "用户原因" },
				          { value: 1, text: "问题处理用户认可" },
				        ],
				image: 0,
				imageStyles: {
					width: 80,
					height: 80
				},
				datetimesingle:'',
				regiPerson: '', // 选择的Item
				peopleList: [], // 登记人选择列表
				peopleList2: [], // 登记人选择列表
				tmpImageUrl: [],
				formData: {
					currentProgress: '',
					currentLink: '',
					solutionCategory: '',
					solutionSubclass: '',
					existenceDuration: '',
					existenceDurationName: '',
					specificScheme: '',
					longitude: '',
					latitude: '',
					longitudeLanding: '',
					latitudeLanding: '',
					projectProcessingProgress: '',
					planImplementation: '',
					userEvaluationIntention: '',
					uploadClosedLoopRecording: '', //上传录音
					complaintsAppeaseThoseResponsible: '12312',
					projectStatus: '',
					reserveCustomerTime: '',
					problemType:'',
					complaintsHandlingUnit:'',
					closed: '',
					unclosedReason:'',
					complaintHandlingRemarks:'',
					approved:'',
					planFailedReason:''
				},
				//workOrderStatus map
				workOrderStatus_value : ['未接单','已接单','已回单','现场方案','方案审核','方案落地','用户回访评估'],
				rules: {
					approved: {
						rules: [{
							required: true,
							message: '请选择是否同意方案'
						}]
					},
					planFailedReason: {
						rules: [{
							required: false,
							message: '请输入不同意的理由'
						}]
					},
					currentProgress: {
						rules: [{
							required: false,
							message: '当前进展不能为空'
						}]
					},
					currentLink: {
						rules: [{
							required: false,
							message: '当前环节不能为空'
						}]
					},
					solutionCategory: {
						rules: [{
							required: false,
							message: '解决方案大类不能为空'
						}]
					},
					solutionSubclass: {
						rules: [{
							required: false,
							message: '解决方案小类'
						}]
					},
					existenceDuration: {
						rules: [{
							required: false,
							message: '请勾选是否存在工期'
						}]
					},
					existenceDurationName: {
						rules: [{
							required: false,
							message: '工期名称不能为空'
						}]
					},
					specificScheme: {
						rules: [{
							required: false,
							message: '具体方案不能为空'
						}]
					},
					longitude: {
						rules: [{
							required: false,
							message: '经度不能为空'
						}]
					},
					latitude: {
						rules: [{
							required: false,
							message: '纬度不能为空'
						}]
					},
					projectProcessingProgress: {
						rules: [{
							required: false,
							message: '方案处理进展不能为空'
						}]
					},
					planImplementation: {
						rules: [{
							required: false,
							message: '方案是否落地不能为空'
						}]
					},
					userEvaluationIntention: {
						rules: [{
							required: false,
							message: '用户10分评价意愿不能为空'
						}]
					},
					uploadClosedLoopRecording: {
						rules: [{
							required: false,
							message: '录音文件不能为空'
						}]
					},
					complaintsAppeaseThoseResponsible: {
						rules: [{
							required: false,
							message: '投书安抚责任人不能为空'
						}]
					},
					reserveCustomerTime: {
						rules: [{
							required: false,
							message: '预约客户时间不能为空'
						}]
					},
					problemType: {
						rules: [{
							required: false,
							message: '投诉原因不能为空'
						}]
					},
					closed:{
						rules: [{
							required: false,
							message: '请选择问题是否闭环'
						}]
					},
					unclosedReason:{
						rules: [{
							required: false,
							message: '不闭环原因不能为空'
						}]
					},
					complaintHandlingRemarks:{
						rules: [{
							required: false,
							message: '投诉处理备注不能为空'
						}]
					},
				},
				params: {},
				webviewStyles: {
					progress: {
						color: "#FF3333"
					}
				},
				status: '',
				query: {
					pageNum: 1,
					pageSize: 10
				},
				complaintFieldFile: {
					filePath: ''
				},
				imgList: [],
				addImg: '',
				recordingFile: null,
				recordUrl: '', //录音文件
				reassignmentUserId: '',
				SubList: [],

			}
		},
		props: {
			src: {
				type: [String],
				default: null
			}
		},
		onLoad(event) {
			this.id = event.id;
			console.log(event);
			this.getTitle();
			this.getUser()
			this.params = event
			if (event.title) {
				uni.setNavigationBarTitle({
					title: event.title
				})
			}
		},
		methods: {
			// 获取链接地址
			writeBytes(url) {
				let str = config.baseUrl + '/system/complaintFieldFile/writeBytes?path=' + url
				return str;
			},
			//取录音文件名称
			getName(url) {
				const parts = url.split('/');
				const recordPart = parts.pop()
				const recordName = recordPart.split('_')[0];

				if (recordName) {
					return recordName
				} else {
					return '录音文件'
				}
			},
			// 选择大类
			handleSelectChange(e) {
				if (e) {
					this.solutionSubList(e)
				}
			},
			// 选择小类
			solutionSubList(e) {
				let params = {
					pageNum: 1,
					pageSize: 999,
					parentNode: e
				}
				solutionSubclassList(params).then(res => {
					if (res.code == 200) {
						this.SubList = res.rows
					}
				})
			},
			getTitle() {
				this.imgList = [];
				uni.showLoading({
					title: '加载中...'
				});
				getComplaint(this.id).then(res => {
					this.$modal.closeLoading()
					if (res) {
						this.formData = res.data;
						this.formData.reserveCustomerTime = this.formData.reserveCustomerTime || '';
						this.formData.planFailedReason = ''
						this.formData.approved = ''
						console.log(this.formData.reserveCustomerTime);
						res.data.pictureFileList.forEach((res, index) => {
							let str = config.baseUrl + '/system/complaintFieldFile/writeBytes?path=' + res
								.filePath
							this.imgList.push({
								url: str
							})
						});
						this.handleSelectChange(this.formData.solutionCategory);
					}
				}).finally((res) => {
					uni.hideLoading();
				}).catch(() => {
					if (this.captchaEnabled) {
						this.getCode()
					}
				})
			},
			getUser() {
				this.peopleList = []
				userList(this.query).then(res => {
					if (res) {
						this.peopleList2 = res.rows;
						res.rows.forEach(item => {
							this.peopleList.push({
								text: item.nickName,
								value: item.userId,
								row: item
							});
						});
					}
				})
			},

			personInput(value) {},
			personSelect(str) {
				this.reassignmentUserId = str.userId
			},
			cancel(e) {
				if (e == 0) {
					this.$refs.problem.close();
				} else if (e == 1) {
					uni.showLoading({
						title: '退回中...'
					});
					sendBack({
						complaintId: this.id
					}).then(res => {
						if (res.code == 200) {
							uni.navigateBack();
						}
					}).finally((res) => {
						this.$refs.problem.close();
						uni.hideLoading();
					}).catch((res) => {
						uni.showToast({
							title: '退回失败',
							icon: 'error',
							duration: 2000 // 显示时间，单位ms
						});
					})
				} else {
					uni.showLoading({
						title: '转派中...'
					});
					let str = {
						reassignmentUserId: this.reassignmentUserId,
						complaintId: this.id
					}
					reassignment(str).then(res => {
						if (res.code == 200) {
							uni.navigateBack();
						}
					}).finally((res) => {
						uni.navigateBack();
						this.$refs.problem.close();
						uni.hideLoading();
					}).catch((res) => {
						uni.showToast({
							title: '转派失败...',
							icon: 'error',
							duration: 2000 // 显示时间，单位ms
						});
					})
				}

			},
			openuploadImg() {
				this.$refs.child.takeAlbum();
			},
			deletes(index) {				
				this.complaintFieldFile.filePath = new URL(this.imgList.splice(index,1)[0].path).searchParams.get('path')
				deleteFileByPath(this.complaintFieldFile)
				// deleteFile(this.formData.pictureFileList[index].id)
				this.formData.pictureFileList.splice(index, 1)
				this.imgList.splice(index,1)
			},
			// 接收传过来的值
			receive(option) {
				if(this.formData.projectStatus==='2'){
					this.formData.longitude = option.longitude
					this.formData.latitude = option.latitude
				}else{
					this.formData.longitudeLanding = option.longitude
					this.formData.latitudeLanding = option.latitude
				}
				this.addImg = option.imgArr
				this.image = this.image + 1;
				this.uploadFiles(0)
			},
			// 上传图片
			upLoadPic(e) {
				console.log(e.tempFiles[0].extname)
				console.log('1111', e)
				// 触发上传图片
				this.image = this.image + 1
				const tempFilePaths = e.tempFilePaths;
				console.log('2222', tempFilePaths)
				//获取图片临时路径
				const imgUrl = tempFilePaths[0]
				let that = this
				this.httpRequest(imgUrl).then(res => {
					console.log(res, '成功转换为blob文件');
					let that1 = that
					new ImageCompressor(
						res, // 需要压缩的图片文件
						{
							quality: 0.4, // 压缩的比率
							success: function(res) {
								//  res 转换之后的文件流
								// 压缩成功之后默认是blob文件，那么这里采用原生的文件转换，其实就是新创建一个文件
								// let files = new window.File([res], res.name, { type: res.type })
								console.log('压缩成功！')
								// 现在得到的就是标准的文件流，可以直接上传服务器  
								// 当然如果服务器默认接受blob文件，那就当上面描述的都是废话可自动删除、或注释掉

								// 保存压缩后的图片路径
								let img = URL.createObjectURL(res)

								setTimeout(() => {
									let data = {
										name: 'file',
										filePath: img,
										formData: {
											complaintId: that.id,
											fileType: 'picture',
											projectStatus: that.formData.projectStatus,
										},

									}
									console.log('湖附近撒', data)
									uploadCommonFile(data).then(response => {
										const pic = {
											url: config.baseUrl +
												'/system/complaintFieldFile/writeBytes?path=' +
												response.fieldFileUrl,
											extname: 'png',
											name: 'picture'
										}
										that.imgList.push(pic)
										console.log('成功上传图片！', response)
										that.image = that.image - 1

									})
								}, 100)
							},
							error(e) {
								console.log(e);
								this.image = this.image - 1
							}
						}
					)
				}).catch(err => {
					console.log('5555', err)
					this.image = this.image - 1
				})
				onLoad(event)
				console.log('获取图片列表', that.imgList)
			},

			// 录音上传
			uploadRecord() {
				uni.chooseFile({
					count: 1,
					type: 'audio',
					success: (res) => {
						this.recordUrl = res.tempFiles;
						this.uploadFiles(1);
					},
				})
			},
			//视频上传
			uploadFiles(index) {
				var that = this
				if (index == 0) {
					uni.showLoading({
						title: '图片上传中'
					});
					uni.uploadFile({
						url: baseUrl + '/system/complaintFieldFile/upload', // 服务器上传接口地址
						filePath: this.addImg,
						name: 'file', // 服务器对应的字段名
						header: {
							'Authorization': 'Bearer ' + getToken(), // 示例：设置Token
							// 其他自定义请求头
						},
						formData: {
							'complaintId': this.id,
							'fileType': 'picture'
						},
						success: (uploadFileRes) => {
							let img = JSON.parse(uploadFileRes.data).fieldFileUrl
							this.imgList.push({
								url: this.addImg,
								extname: 'png',
								name: 'picture'
							});
							// this.form.worksList[index].workFile = Json.parse(uploadFileRes);
							uni.hideLoading();
						},
						fail: (uploadFileErr) => {
							uni.showToast({
								icon: 'none',
								title: '图片上传失败,请稍后再试'
							});
							uni.hideLoading();
						}
					});
				} else if (index == 1) {
					uni.showLoading({
						title: '录音上传中'
					});
					uni.uploadFile({
						url: baseUrl + '/system/complaintFieldFile/upload', // 服务器上传接口地址
						filePath: this.recordUrl[0].path,
						name: 'file', // 服务器对应的字段名
						header: {
							'Authorization': 'Bearer ' + getToken(), // 示例：设置Token
							// 其他自定义请求头
						},
						formData: {
							'complaintId': this.id,
							'fileType': 'recording'
						},
						success: (upload) => {
							this.formData.recordingFileList.push({
								filePath: JSON.parse(upload.data).fieldFileUrl
							})
							uni.hideLoading();
						},
						fail: (uploadFileErr) => {
							uni.showToast({
								icon: 'none',
								title: '图片上传失败,请稍后再试'
							});
							uni.hideLoading();
						}
					});
				}
			},
			// 传入blob路径，.then()获取blob文件
			httpRequest(src) {
				let that = this
				return new Promise((resolve, reject) => {
					let xhr = new XMLHttpRequest()
					xhr.open('GET', src, true)
					xhr.responseType = 'blob'
					xhr.onload = function(e) {
						if (this.status == 200) {
							let myBlob = this.response
							let files = new window.File(
								[myBlob],
								myBlob.type, {
									type: myBlob.type
								}
							) // myBlob.type 自定义文件名
							resolve(files)
						} else {
							reject(false)
						}
					}
					xhr.send()
				})
			},
			radioChange(e) {
				this.formData.existenceDuration = e.detail.value
			},
			radioChange2(e) {
				this.formData.planImplementation = e.detail.value
			},
			radioChange3(e) {
				this.formData.uploadClosedLoopRecording = e.detail.value
			},
			closedChange(e){
				this.formData.approved = e.detail.value;
				if(e.detail.value=='1'){
					this.rules.planFailedReason.rules[0].required = true;
				}
			},
			openPupoe() {
				this.regiPerson = ''
				this.$refs.problem.open()
			},
			chooseReserveCustomerTime(){
						  this.formData.reserveCustomerTime = this.datetimesingle;
			},
			changeProblemType(e){
				this.formData.problemType = e,detail.value;
				console.log(this.formData.problemType);
			},
			onSubmit(event) {
				// 触发表单验证
				// const formRefName = 'form'+this.formData.projectStatus;
				// console.log(formRefName)
				this.$refs.form.validate().then((res) => {
					console.log(this.formData)
					uni.showLoading({
						title: '提交中...'
					});
					setReviewOpinions(this.formData).then(res => {
						if (res.code == 200) {}
					}).finally(() => {
						uni.showToast({
							title: '提交成功',
							icon: 'none'
						});
						uni.hideLoading();
						uni.navigateBack();
					}).catch(() => {
						uni.showToast({
							title: '提交失败',
							icon: 'none'
						});
					})
				}).catch((err) => {
					console.log("表单验证失败")
					let key = '#' + err[0].key
					uni.pageScrollTo({
						selector: key,
						duration: 500,
						offsetTop: 10,
						success: function() {

						}
					})

				});
			}
		},
	}
</script>
<style scoped lang="scss">
	.form {
		margin: 20upx;
		background-color: #fff;
		padding: 20upx 30upx;
		font-size: 20px;
	}

	.icones {
		color: #efefef;
	}

	/deep/.uni-forms-item {
		display: block;
	}

	/deep/.uni-forms-item__label {
		font-size: 40upx;
	}

	.picker {
		width: 100%;
		display: flex;
		justify-content: space-between;
	}

	.picker2 {
		width: 100%;
		text-align: right;
	}

	.radio {
		font-size: 40rpx;
		margin-left: 20rpx;
	}

	/deep/.uni-easyinput__placeholder-class {
		font-size: 40rpx;
	}

	/deep/.uni-select__input-placeholder {
		font-size: 40rpx;
	}

	/deep/.uni-select {
		height: 90rpx;
	}

	.btn-row {
		position: fixed;
		bottom: 0upx;
		width: 100%;
		padding: 10upx 20upx;
		z-index: 99;
		box-sizing: border-box;
		background-color: #fff;
		border-top: 1upx solid #f2f2f2;
		box-shadow: 6upx 0upx 9upx 0upx rgba(0, 0, 0, 0.2);
	}

	.btn-save {
		background-color: transparent;
		width: 45%;
		font-size: 34rpx;
		border-radius: 50upx;
		color: #2DCABE;
		border: 1px solid #2DCABE;
	}

	.btn-save2 {
		width: 45%;
		background-color: #2DCABE;
		height: 90upx;
		line-height: 90upx;
		font-size: 34rpx;
		border-radius: 50upx;
	}

	.tenant {
		font-size: 40rpx;
		padding: 24upx;
		width: 98%;
		width: 600upx;
		background-color: white;
		border-radius: 10upx;
	}

	.example {
		display: flex;
		justify-content: space-between;
		font-size: 40rpx;
		font-weight: bold;
		margin-bottom: 26rpx;
	}

	.photo {
		border: 1px solid rgb(238, 238, 238);
		border-radius: 3px;
		display: inline-grid;
		width: 107px;
		line-height: 107px;
		text-align: center;
		align-items: center;
	}

	.postvideo {
		position: relative;
	}

	.openWater {
		position: fixed;
		z-index: 999;
		left: 0px;
	}
</style>